package service

import (
	"context"
	"fmt"
	"mime/multipart"
	"os"
	"singo/serializer"

	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
)

// UploadFileService 管理用户注册服务
type UploadFileService struct {
	File     string `form:"file" json:"file" binding:"required"`
	FileName string `form:"fileName" json:"fileName" binding:"required"`
	FileSize string `form:"fileSize" json:"fileSize" binding:"required"`
}

// 自定义返回值结构体
// type MyPutRet struct {
// 	Key    string
// 	Hash   string
// 	Fsize  int64
// 	Bucket string
// 	Name   string
// }

// UploadFiletoQiniu 上传文件到七牛云对象存储inpm空间
func UploadFiletoQiniu(file multipart.File, fileName string, fileSize int64) serializer.Response {
	// 七牛Go开发文档：https://developer.qiniu.com/kodo/1238/go
	bucket := os.Getenv("QINIU_BUCKET")
	putPolicy := storage.PutPolicy{
		Scope:        bucket,
		ReturnBody:   `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":$(x:name)}`,
		CallbackBody: `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":$(x:name)}`,
	}
	accessKey := os.Getenv("QINIU_ACCESS_KEY")
	secretKey := os.Getenv("QINIU_SECRET_KEY")
	mac := qbox.NewMac(accessKey, secretKey)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuanan
	// 是否使用https域名
	cfg.UseHTTPS = true
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = true
	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	// ret := MyPutRet{
	// 	Key:  os.Getenv("QINIU_SPACE") + fileName,
	// 	Name: fileName,
	// }
	// 可选配置
	putExtra := storage.PutExtra{}
	err := formUploader.PutWithoutKey(context.Background(), &ret, upToken, file, fileSize, &putExtra)
	if err != nil {
		fmt.Println(err)
		return serializer.ParamErr("上传失败", nil)
	}
	return serializer.BuildUploadFileResponse("https://cdn.inpm.top/" + ret.Key)
}
